package com.service;

import com.curve.UserCurve;
import com.curve.CurvePoint;
import com.lordor.security.Account;
import com.lordor.framework.bean.FastServiceFactory;
import com.lordor.framework.query.*;
import com.lordor.framework.query.expression.Expression;

import java.util.Date;
import java.util.List;

/**
 * User: lyj
 * Date: 2011-11-30
 * Time: 14:48:17
 */
public class CurveService implements ICurveService{

    public UserCurve createUserCurve(Account user, String title) {
        UserCurve uc=new UserCurve();
        uc.setUser(user);
        uc.setTitle(title);
        FastServiceFactory.getPersistence().save(uc);
        return uc;
    }


    public UserCurve findUserCurveById(String sysid) {
        return (UserCurve) FastServiceFactory.getPersistence().findByPrimaryKey(sysid,UserCurve.class);
    }


    private CurvePoint findCurvePointById(String sysid) {
        return (CurvePoint) FastServiceFactory.getPersistence().findByPrimaryKey(sysid,CurvePoint.class);
    }

    public void addCurvePoint(String curveId, Date pointDate) {
       UserCurve uc=findUserCurveById(curveId);
        CurvePoint cp=new CurvePoint();
        cp.setUserCurve(uc);
        cp.setUser(uc.getUser());
        cp.setPointDate(pointDate);
        FastServiceFactory.getPersistence().save(cp);
    }

    public void removeCurvePoint(String curveId, String pointId) {
        CurvePoint cp=findCurvePointById(pointId);
        FastServiceFactory.getPersistence().delete(cp);
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void deleteUserCurve(String curveId) {
        UserCurve uc=findUserCurveById(curveId);
        uc.setValid(false);
        //To change body of implemented methods use File | Settings | File Templates.
    }


    public QueryResult queryMyCurves(Account user, PageViewer pv) {
          IQuery q = new Query();
        q.add(Expression.eq("user.sysId", user.getSysId()));
        q.add(Expression.eq("valid", Boolean.TRUE));
        q.addOrder(Order.desc("createDate"));
        QueryResult qr = FastServiceFactory.getPersistence().find(q, UserCurve.class, pv);
        return qr;
    }


    public List findMyCurvePoints(Account user, String id) {
        String hql=" from "+CurvePoint.class.getName()+" cp where cp.userCurve.sysId='"+id+"' and cp.user.sysId='"+user.getSysId()+"'";
        return FastServiceFactory.getPersistence().findByClause(hql);
    }
}
